public class AllocateCityMonthlyBuffer
{
    public String msg{get;set;}
    public String IdSelect{get;set;}
    public Boolean DisplayApprove{get;set;}
    public Boolean DisplaySubmit{get;set;}
    public Boolean DisplaySave{get;set;}
    public Boolean DisplayAllocate{get;set;}

    public String CityHead;
    public String SalesCity;

    public Decimal TotalAdjustKG{get;set;}
    public Decimal TotalAllocatedKG{get;set;}
    public Decimal TotalRemainingKG{get;set;}
    public Decimal TotalAdjustRMB{get;set;}
    public Decimal TotalAllocatedRMB{get;set;}
    public Decimal TotalRemainingRMB{get;set;}    

    public Boolean ForUpdate;
    public String CityBufferName;
    
    List<CityBudget__c> SelectedRecordList = new  List<CityBudget__c>();
    List<CityBudget__c> SelectedBudgetList = new List<CityBudget__c>();

    CityBudget__c NeedAllocateBuffer = new CityBudget__c();
    List<CityMonthlyBudget__c> RsmMonthlyBuffer = new List<CityMonthlyBudget__c>();    
    PE_Sample_Management__c PESM = new PE_Sample_Management__c();
      
    Integer Inequality = 0;    

    public String UrlId
    {
        get{  
            String AllString = System.currentPageReference().getParameters().get('id');  
            CityBufferName = AllString.substring(16,AllString.length());
            UrlId = AllString.substring(0,15);
            return  UrlId;  
        }  
        set;
    }
        
    public CityBudget__c CityBudget{
         get{
             if(CityBudget== null)
                 CityBudget= new CityBudget__c();
             return CityBudget;
         }
         set;
    }  
    public CityMonthlyBudget__c CityMonthlyBudget{
         get{
             if(CityMonthlyBudget== null)
                 CityMonthlyBudget= new CityMonthlyBudget__c();
             return CityMonthlyBudget;
         }
         set;
    }
    public List<CityMonthlyBudget__c> AmountBudget{
         get{
             if(AmountBudget== null)
                 AmountBudget= new List<CityMonthlyBudget__c> ();
             return AmountBudget;
         }
         set;
    }
    
    public Sub_Region_Budget__c SRB {
         get{
             if(SRB == null)
                 SRB = new Sub_Region_Budget__c();
             return SRB ;
         }
         set;
    }      
        
    public List<TableItemControl> TableItemsDown{         
        get{
             if(TableItemsDown== null)
                 TableItemsDown= new List<TableItemControl>();
             return TableItemsDown;
         }
        set;
    }    
    
    
    public List<CityBudget__c> ExistRecord = new List<CityBudget__c>();
    public CityBudget__c SelectedRecord{
        get{        
             if(SelectedRecord== null)
                 SelectedRecord= new CityBudget__c();
             return SelectedRecord;
        }  
        set;
    }
    public List<Place__c> pList = new  List<Place__c>();  
    User cu  = [Select Name,UserRoleId,ProfileId,Title__c From User Where Id =:UserInfo.getUserId()];
    UserRole ur = [Select Id,Name,ParentRoleId  From UserRole Where Id =: cu.UserRoleId]; 

    UserRole RoleNMKD = [Select u.Name, u.Id From UserRole u Where u.Name =: GlobalProperties.RoleNMKD];
    RecordType BufferRecord = [Select r.Name, r.Id From RecordType r Where Name =: GlobalProperties.CityMonthlyBuffer];
    Profile RSM= [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileRSM_M];
    Profile RSTM= [Select p.Name, p.Id From Profile p Where p.Name =: GlobalProperties.ProfileRSM_TM];
    
    
    // get the city list                
    public List<SelectOption> options{
        get{
             if(options == null)
                options = new List<SelectOption>();
            else
                options.clear();
                
            CityBudget.Year__c = SRB.Year__c;
            CityBudget.Rate__c = SRB.Rate__c;
            CityBudget.TotalBudgetkg__c = SRB.Total_budget_kg__c;
            CityBudget.TotalBudgetRMB__c = SRB.Total_budget_RMB__c;
            options.add(new SelectOption('1',' '));                    

           List<CityBudget__c> CityBufferList = [Select  c.id,c.SalesCity__c,c.CityHead__c,c.CityHead__r.name  From CityBudget__c c 
               Where c.name =: CityBufferName and c.SubRegionBudget__c =: UrlId and c.AdjustmentSubmit__c =: false  and c.ownerid !=: cu.id ];   
           
           for(CityBudget__c c : CityBufferList)
           {
               options.add(new SelectOption(c.CityHead__c + ':' + c.SalesCity__c ,c.SalesCity__c+':'+c.CityHead__r.name ));
           }                 

            return  options;
        }
        set;
    } 
    

    
    public PageReference actionSupport()
    {
        msg = null;
        ForUpdate = false;
        Decimal TotalThisYearPEConversionValue = 0; 
        Decimal TotalSubRegionThisYearInMarketSalesValue = 0;
       List<AggregateResult> BufferAmount = [Select sum(c.BudgetRMB__c) RMB , sum(c.BudgetKg__c)KG From CityMonthlyBudget__c c Where 
           c.RecordType__c =: 'Buffer' and  c.SalesCity__c =: NeedAllocateBuffer.SalesCity__c and c.CityBudget__r.SubRegionBudget__c =: NeedAllocateBuffer.SubRegionBudget__c  and CityBudget__r.NeedRSMAllocate__c =: false];    
       if((Decimal)BufferAmount[0].get('KG') > 0)
       {
           TotalAllocatedKG  = (Decimal)BufferAmount[0].get('KG');
       }
       else
       {
           TotalAllocatedKG  = 0 ;
       } 
       if((Decimal)BufferAmount[0].get('RMB') > 0)
       {
           TotalAllocatedRMB = (Decimal)BufferAmount[0].get('RMB'); 
       }
       else
       {
           TotalAllocatedRMB = 0;
       }
        
        for(SelectOption s : options)
        {
            if(s.getValue() == IdSelect)
            {
                CityHead = s.getValue().split(':', 2)[0];
                SalesCity = s.getLabel().split(':', 2)[0];            
            }
        }
        
        if(ExistRecord.size() > 0 ){
            TableItemsDown.clear();
            AmountBudget.clear();
            
            List<AggregateResult> TotalLastYearInMarketSales = [Select sum(InMarketSaleskg__c)InMarketSales, Month__c Mon From 
               InMarketSales__c Where InMarketSaleskg__c > 0 and Year__c =: integer.valueof(SRB.Year__c)-1 and SalesCity__c =: SalesCity group by Month__c]; 
            List<AggregateResult> TotalThisYearInMarketSales = [Select sum(InMarketSalesForcast__c)InMarketSales, Month__c Mon From 
               InMarketSales__c Where InMarketSalesForcast__c > 0 and Year__c =: integer.valueof(SRB.Year__c)  and SalesCity__c =: SalesCity group by Month__c];                 
        
            List<AggregateResult> TotalLastYearPEShipment = [Select sum(KG__c)kg,Month__c Mon From Shipment__c Where KG__c > 0 and   Year__c =: integer.valueof(SRB.Year__c)-1 and SalesCity__c =: SalesCity and CalcInKg__c =: true group by Month__c];
    
            List<AggregateResult> SubRegionLastYearPEConversion = [Select sum(PE_conversion_achieve__c)TotalIn,Month__c Mon  From 
                                          Achieve__c Where PE_conversion_achieve__c > 0 and   Year__c =: string.valueof(integer.valueof(SRB.Year__c)) and Sales_city__c =: SalesCity group by Month__c];
            
            List<AggregateResult> SubRegionThisYearPEConversion = [Select sum(PE_Conversion_forecast__c)TotalIn,Month__c Mon  From 
                                          Achieve__c Where PE_Conversion_forecast__c > 0 and   Year__c =: string.valueof(integer.valueof(SRB.Year__c)) and Sales_city__c =: SalesCity group by Month__c];


        RsmMonthlyBuffer = [Select c.Year__c, c.ThisYearPESampleKg__c, c.CreatedDate,c.IfRejectThenDel__c,
            c.ThisYearInMarketSalesKg__c, c.SystemModstamp, c.SubRegionalMonthlyBudget__c, c.Name, c.Month__c,
            c.LastYearPESamplekg__c, c.LastYearInMarketSaleskg__c,c.Id, c.CityBudget__c, c.BudgetRMB__c, 
            c.BudgetKg__c From CityMonthlyBudget__c c Where c.CityBudget__c =: NeedAllocateBuffer.id and c.RecordType__c =: 'Buffer'];

        Integer StartMon;
            if(Date.Today().Month() <= 3)
            {
                StartMon = 4;
            }
            else if(Date.Today().Month() <= 6)
            {
                StartMon = 7;
            }
            else if(Date.Today().Month() <= 9)
            {
                StartMon = 10;
            }        
            else if(Date.Today().Month() <= 12)
            {
                StartMon = 1;
            } 

                            
        for(Integer i = StartMon; i < 13;i++)
        {
            TableItemControl T = new TableItemControl();
            T.Str = String.valueof(i);
            
            Decimal LastYearPEShipmentValue = 0;
            Decimal SubRegionLastYearInMarketSalesValue = 0;
            Decimal SubRegionThisYearInMarketSalesValue = 0;                
            Decimal LastYearPEConversionValue = 0;
            Decimal ThisYearPEConversionValue = 0;
            for(AggregateResult ag : TotalLastYearInMarketSales)
            {
                if(Integer.valueof(ag.get('Mon'))== i)
                {
                    SubRegionLastYearInMarketSalesValue = (Decimal)ag.get('InMarketSales');
                }
            }                
            for(AggregateResult ag : TotalThisYearInMarketSales)
            {
                if(Integer.valueof(ag.get('Mon'))== i)
                {
                    SubRegionThisYearInMarketSalesValue = (Decimal)ag.get('InMarketSales');
                    if(SubRegionThisYearInMarketSalesValue > 0)
                        TotalSubRegionThisYearInMarketSalesValue += SubRegionThisYearInMarketSalesValue;
                }
            }  
            for(AggregateResult ag : TotalLastYearPEShipment)
            {
                if(Integer.valueof(ag.get('Mon'))== i)
                {
                    LastYearPEShipmentValue = (Decimal)ag.get('kg');
                }
            }  
 
            for(AggregateResult ag : SubRegionLastYearPEConversion)
            {
                if(Integer.valueof(ag.get('Mon'))== i)
                {
                    LastYearPEConversionValue = (Decimal)ag.get('TotalIn');
                }
            }                                                  
            for(AggregateResult ag : SubRegionThisYearPEConversion)
            {
                if(Integer.valueof(ag.get('Mon'))== i)
                {
                    ThisYearPEConversionValue = (Decimal)ag.get('TotalIn');
                    if(ThisYearPEConversionValue > 0)
                        TotalThisYearPEConversionValue += ThisYearPEConversionValue;    
                }
            }

            if(LastYearPEShipmentValue > 0)
                T.CMB.LastYearInMarketSaleskg__c= SubRegionLastYearInMarketSalesValue / LastYearPEShipmentValue;
            else
                T.CMB.LastYearInMarketSaleskg__c = 0;
            if(LastYearPEConversionValue > 0)   
                T.CMB.LastYearPESamplekg__c = LastYearPEShipmentValue / LastYearPEConversionValue;
            else
                T.CMB.LastYearPESamplekg__c = 0;

            T.CMB.ThisYearInMarketSalesKg__c = 0;
            T.CMB.ThisYearPESampleKg__c = 0;
            T.CMB.ConversionForcast__c = ThisYearPEConversionValue;
            T.CMB.InMarketValueHide__c = SubRegionThisYearInMarketSalesValue;     
                             
            TableItemsDown.add(T);
        }


            
           List<CityBudget__c> SelectedRecordList = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c, 
                c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, 
                c.SystemModstamp, c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c,  c.Region__c, 
                c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
                c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,  c.CityHead__c,
                c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Changed__c From CityBudget__c c Where 
                c.Name =: SRB.Year__c +'年'+ SalesCity + '专业样品管理' and 
                c.CityHead__c =: CityHead and c.SubRegionBudget__c =: UrlId ];  //
              
            if(SelectedRecordList.size() > 0){
                SelectedRecord = SelectedRecordList[0];          
                
                List<CityMonthlyBudget__c> existMonBud = [Select c.Year__c, c.ThisYearPESampleKg__c, c.IfRejectThenDel__c,
                    c.ThisYearInMarketSalesKg__c, c.SystemModstamp, c.SubRegionalMonthlyBudget__c, c.Name, c.Month__c,
                    c.LastYearPESamplekg__c, c.LastYearInMarketSaleskg__c,c.Id, c.CityBudget__c, c.BudgetRMB__c, 
                    c.BudgetKg__c From CityMonthlyBudget__c c Where c.CityBudget__c =: SelectedRecord.id and c.RecordType__c =: 'Buffer'];
                List<CityMonthlyBudget__c> existMonBudget = [Select c.Name, c.Month__c,c.Id, c.CityBudget__c,
                    c.BudgetKg__c From CityMonthlyBudget__c c Where c.CityBudget__c =: SelectedRecord.id and c.RecordType__c =: 'Budget'];     
                if(existMonBud.size() > 0){
                    ForUpdate = true;
                    for(CityMonthlyBudget__c sr : existMonBud)
                    {
                        for(TableItemControl t1 : TableItemsDown)
                        {
                            if( sr.Month__c == t1.str)
                            { 
                                t1.CMB = sr;
                            }
                        }
                    }
                } 
                if(existMonBudget.size() > 0){
                    for(CityMonthlyBudget__c sr : existMonBudget)
                    {
                        for(TableItemControl t1 : TableItemsDown)
                        {
                            if( sr.Month__c == t1.str)
                            { 
                                t1.CMB.BudgetAllocatedKG__c = sr.BudgetKg__c;
                            }
                        }
                    }
                }                     
            } 
            CityMonthlyBudget__c srmb = new CityMonthlyBudget__c();
            srmb.Name = '合计';
            srmb.ThisYearInMarketSalesKg__c = 0;
            srmb.ThisYearPESampleKg__c = 0;
            srmb.ConversionForcast__c = TotalThisYearPEConversionValue;
            srmb.InMarketValueHide__c = TotalSubRegionThisYearInMarketSalesValue;    
            srmb.BudgetAllocatedKG__c = 0;
            for(TableItemControl t1 : TableItemsDown)
            {
                if(srmb.BudgetAllocatedKG__c > 0)
                    srmb.BudgetAllocatedKG__c += t1.CMB.BudgetAllocatedKG__c;
                else
                    srmb.BudgetAllocatedKG__c = t1.CMB.BudgetAllocatedKG__c;
            }         
            AmountBudget.add(srmb);                       
         }          

        return null;
    } 

    public AllocateCityMonthlyBuffer(){    

        DisplaySave = true;

        SRB = [Select s.total_score__c, s.potential_score__c, s.final_weighting__c, s.Year__c, s.Total_budget_kg__c, 
            s.Total_budget_RMB__c, s.This_year_PE_Sample_kg__c, s.This_year_In_market_sales_kg__c, 
            s.Submit__c, s.Sub_Region__c, s.Sales_City__c, s.Region__c, s.Rate__c, s.Place__c, s.PE_Sample_Management__c, 
            s.OwnerId, s.Name, s.Line_Manager__c, s.Last_year_sales_weighting__c, s.Last_year_conversion_weighting__c, 
            s.Last_year_PE_Sample_kg__c, s.Last_year_In_market_sales_kg__c,s.Id, s.Area__c, s.ApprovedFormula__c ,s.ApprovalStatus__c
            From Sub_Region_Budget__c s Where s.id =: UrlId];
       
       PESM = [Select id, Budget_hold_in_HQ_Budget_allocation_kg__c,Budget_hold_in_HQ_RMB__c From PE_Sample_Management__c Where id =: SRB.PE_Sample_Management__c];

        ExistRecord = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c,AdjustmentSubmit__c,AdjustmentApprove__c, 
            c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, 
            c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c,  c.Region__c, c.RSM__c,
            c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
            c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,  c.ApprovalStatus__c,
            c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Submit__c,c.Changed__c  From CityBudget__c c Where name =: CityBufferName and c.SubRegionBudget__c =: UrlId and NeedRSMAllocate__c =: false ];                      
        
        List<CityBudget__c> NeedAllocateBufferList = [Select c.month__c, c.city__c, c.amount__c, c.Year__c, c.TotalScore__c,AdjustmentSubmit__c,AdjustmentApprove__c, 
            c.TotalBudgetkg__c, c.TotalBudgetRMB__c, c.ThisYearPESamplekg__c, c.ThisYearInMarketSaleskg__c, c.BufferKG__c ,c.BufferRMB__c ,
            c.SubRegion__c, c.SubRegionBudget__c, c.SalesCity__c, c.Region__c, c.RSM__c,
            c.Rate__c, c.PotentialScore__c, c.Place__c, c.OwnerId, c.Name, c.LineManager__c, c.LastYearSalesWeighting__c,
            c.LastYearPESampleKg__c, c.LastYearInMarketSalesKg__c, c.LastYearConversionWeighting__c,  c.ApprovalStatus__c,
            c.Id, c.FinalWeighting__c, c.Area__c, c.Approved__c,c.Submit__c,c.Changed__c  From CityBudget__c c Where name =: CityBufferName and c.SubRegionBudget__c =: UrlId and NeedRSMAllocate__c =: true];                      
        
        NeedAllocateBuffer = NeedAllocateBufferList[0];
        
       TotalAdjustKG = NeedAllocateBuffer.BufferKG__c;
       TotalAdjustRMB = NeedAllocateBuffer.BufferRMB__c;


               
        DisplaySubmit = false;
        DisplaySave = true;
        DisplayApprove = false;      


    }

    public void SetRecord(Boolean Submit)
    {
 
        List<CityMonthlyBudget__c> ExistSubregionalMB = new List<CityMonthlyBudget__c>();
        if(SelectedRecord != null)
            ExistSubregionalMB = [Select id,Month__c,IfRejectThenDel__c From CityMonthlyBudget__c Where CityBudget__c =: SelectedRecord.id ];
        // set table items up
        List<CityMonthlyBudget__c> CityBudgetMonBudgetList = new List<CityMonthlyBudget__c>();
        for(TableItemControl t : TableItemsDown){
            if(T.Str == '合计')
            {
                continue;
            }
            if(t.CMB.BudgetKg__c == null)
                t.CMB.BudgetKg__c = 0;
            if(t.CMB.BudgetAllocatedKG__c == null)
                t.CMB.BudgetAllocatedKG__c = 0;
            if(t.CMB.InMarketValueHide__c == null)
                t.CMB.InMarketValueHide__c = 0;
            if(t.CMB.ConversionForcast__c == null)
                t.CMB.ConversionForcast__c = 0;        
            t.CMB.Name = SRB.Year__c + '年' + SalesCity + t.str + '月专业样品管理';
            t.CMB.Month__c = t.str;
            if(t.CMB.BudgetKg__c == null)
                t.CMB.BudgetKg__c = 0;
            if(t.CMB.BudgetAllocatedKG__c == null)
                t.CMB.BudgetAllocatedKG__c = 0;
            if((t.CMB.BudgetKg__c > 0) &&(SelectedRecord.Rate__c > 0))
                t.CMB.BudgetRMB__c =  t.CMB.BudgetKg__c *  SelectedRecord.Rate__c;
            else
                t.CMB.BudgetRMB__c = 0;
            if(t.CMB.BudgetKg__c + t.CMB.BudgetAllocatedKG__c > 0)
                t.CMB.ThisYearInMarketSalesKg__c = t.CMB.InMarketValueHide__c / (t.CMB.BudgetKg__c + t.CMB.BudgetAllocatedKG__c);
            else
                t.CMB.ThisYearInMarketSalesKg__c = 0;    
            t.CMB.ThisYearInMarketSalesKg__c = t.CMB.ThisYearInMarketSalesKg__c.intValue();
            if(t.CMB.ConversionForcast__c > 0)
                t.CMB.ThisYearPESampleKg__c = (t.CMB.BudgetKg__c + t.CMB.BudgetAllocatedKG__c) / t.CMB.ConversionForcast__c;
            else
                t.CMB.ThisYearPESampleKg__c = 0;
            t.CMB.ThisYearPESampleKg__c = t.CMB.ThisYearPESampleKg__c.intValue();
            t.CMB.IfRejectThenDel__c = true;            
            if(!ForUpdate){          
                t.CMB.CityBudget__c = SelectedRecord.id;
                t.CMB.RecordTypeId = BufferRecord.id;    
            }
            
            CityBudgetMonBudgetList.add(t.CMB);
        }

        if(ForUpdate)
            update CityBudgetMonBudgetList;
        else{
            insert CityBudgetMonBudgetList;
            ForUpdate = true;
        }  

       List<AggregateResult> BufferAmount = [Select sum(c.BudgetRMB__c) RMB , sum(c.BudgetKg__c)KG From CityMonthlyBudget__c c Where 
           c.RecordType__c =: 'Buffer' and  c.SalesCity__c =: SelectedRecord.SalesCity__c and c.CityBudget__r.SubRegionBudget__c =: SelectedRecord.SubRegionBudget__c  and CityBudget__r.NeedRSMAllocate__c =: false];    
       if((Decimal)BufferAmount[0].get('KG') > 0 )
       {
           TotalAllocatedKG  = (Decimal)BufferAmount[0].get('KG');
       }
       else
       {
           TotalAllocatedKG  = 0;
       }
       if((Decimal)BufferAmount[0].get('RMB') > 0)
       {
           TotalAllocatedRMB = (Decimal)BufferAmount[0].get('RMB');
       }
       else
       {
           TotalAllocatedRMB = 0;
       }   
    }


    public PageReference Save()
    {
        
        if(SRB.ApprovedFormula__c == 0)
        {   
            return null;
        }

        Decimal AllocatedNum = decimal.valueof(0);     
        
        for(TableItemControl t : TableItemsDown){
            if(T.Str == '合计')
            {
                continue;
            }
            if((t.CMB.BudgetKg__c != null)&&(t.CMB.BudgetKg__c > 0)){
                if((AllocatedNum == null)||(AllocatedNum == 0))
                    AllocatedNum = t.CMB.BudgetKg__c;
                else
                    AllocatedNum += t.CMB.BudgetKg__c;
            }    
        } 
        
        SetRecord(false);
        
        NeedAllocateBuffer.Allocated__c = true;
        update NeedAllocateBuffer;  
        msg = null;    
        return null;
    }
            
    public PageReference Cancel()
    { 
        if(TotalAllocatedKG  != TotalAdjustKG)
        {
            msg = '请完成分配！';
            return null;
        } 
        pageReference pr = page.AdjustCityMonthlyBudget;
        pr.getParameters().put('id', UrlId);
        return pr;
    }

    
    static testMethod void OverrideViewTest()
    {
    
    }
 
}